package com.overseasShopping.Action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.overseasShopping.Biz.UserBiz;
import com.overseasShopping.pojo.User;

public class LoginAction extends ActionSupport{
	private String userId;
	private String password;
	private UserBiz userBiz;
	private String verification;
	
	
	
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	public void setVerification(String verification) {
		this.verification = verification;
	}
	

	
	public UserBiz getUserBiz() {
		return userBiz;
	}
	public void setUserBiz(UserBiz userBiz) {
		this.userBiz = userBiz;
	}

	@Override
	public String execute() throws Exception {
		Map<String, Object> gap=ActionContext.getContext().getSession();
		gap.put("inputUserId",userId);
		gap.put("inputPassword","");
		gap.put("userError","");
		gap.put("inputPassword",password);
		User user=userBiz.login(userId,password);
		if(user!=null){
			gap.put("user", user);
			String pathname=ServletActionContext.getServletContext().getRealPath("/")+"uImg/"+userId+".jpg";
			File file=new File(pathname);
			FileOutputStream os=new FileOutputStream(file);
			InputStream img = user.getDetailUser().getUimage().getBinaryStream();
			byte[] b = new byte[img.available()];
			img.read(b);
			os.write(b);
			os.flush();
			os.close();
			return SUCCESS;
			}else {
				gap.put("userError", "用户密码不匹配！");
				return ERROR;
			}
	}
	public String sureVerification() throws Exception {
		HttpServletResponse response=ServletActionContext.getResponse();
		PrintWriter pw=response.getWriter();
		Map<String, Object> gap=ActionContext.getContext().getSession();
		String oldVerification=(String) gap.get("randomStr");
		if(verification!=null&&verification.equals(oldVerification)){
			pw.write("success");
		}else{
			pw.write("fail");
		}
		pw.flush();
		pw.close();
		return null;
	}
	
	
	
}
